package demo2;
import java.util.*;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-07-05
 * Time: 15:37
 */
public class MyTreeSet {


    public static void main(String[] args) {
        //使用比较器进行排序
        //让集合方法接收comparator的实现类对象，重写compareTo方法
        TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int num = o1.getAge() - o2.getAge();
                int num1 = num==0?o1.getName().compareTo(o2.getName()):num;
                return num1;
            }
        });
        Student s1 = new Student("张三",18);
        Student s2 = new Student("李四",18);
        Student s3 = new Student("王二麻子",28);
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);

        for (Student student : treeSet) {
            System.out.println(student);
        }
    }


    public static void main2(String[] args) {
        //使用comparable进行自然排序比较
        TreeSet<Student> treeSet = new TreeSet<>();
        Student s1 = new Student("张三",18);
        Student s2 = new Student("李四",18);
        Student s3 = new Student("王二麻子",28);
        treeSet.add(s1);
        treeSet.add(s2);
        treeSet.add(s3);
        //compareTO也要改写
        //1 升序
        //0 存储顺序
        //-1降序
        //无参构造是利用自然排序方式进行排序的
        //需要实现comparable接口，重写compareTo方法
        //不应该只利用主要条件来写，主要条件和次要条件一起进行比较
        for (Student student : treeSet) {
            System.out.println(student);
        }

    }


    public static void main1(String[] args) {
        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(5);
        treeSet.add(4);
        treeSet.add(3);
        treeSet.add(2);
        treeSet.add(1);
        for (Integer num : treeSet) {
            System.out.print(num+" ");
        }
    }

}
